package com.marry.consumer.config;

import com.marry.consumer.listener.MailMessageListenerAdapter;
import com.rabbitmq.client.ConnectionFactory;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

/**
 * @author ml
 * @create 2017-08-03--15:39
 */
@Configuration
@PropertySource(value = {"classpath:application.properties"})
public class RabbitMQConfig {


    @Autowired
    private Environment env;

    @Bean
    public ConnectionFactory connectionFactory(){
        ConnectionFactory connectionFactory=new ConnectionFactory();
        connectionFactory.setHost(env.getProperty("mq.host"));
        connectionFactory.setPort(Integer.parseInt(env.getProperty("mq.port")));
        connectionFactory.setUsername(env.getProperty("mq.username"));
        connectionFactory.setPassword(env.getProperty("mq.password"));
        return connectionFactory;
    }

    @Bean
    public CachingConnectionFactory cachingConnectionFactory(){
        return new CachingConnectionFactory(connectionFactory());
    }

    @Bean
    public RabbitTemplate rabbitTemplate(){

        RabbitTemplate rabbitTemplate=new RabbitTemplate(cachingConnectionFactory());
        rabbitTemplate.setChannelTransacted(true);
        return rabbitTemplate;
    }

    @Bean
    public RabbitAdmin rabbitAdmin(){
        return new RabbitAdmin(cachingConnectionFactory());
    }

    @Bean
    public SimpleMessageListenerContainer listenerContainer(@Autowired MailMessageListenerAdapter mailMessageListenerAdapter){
        String queueName=env.getProperty("mq.queue").trim();

        SimpleMessageListenerContainer simpleMessageListenerContainer=new SimpleMessageListenerContainer(cachingConnectionFactory());

        simpleMessageListenerContainer.setQueueNames(queueName);

        simpleMessageListenerContainer.setMessageListener(mailMessageListenerAdapter);

        //手动ack
        simpleMessageListenerContainer.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        return simpleMessageListenerContainer;
    }


}
